<script setup lang="ts">
import { onMounted, reactive, ref, inject } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

interface ManagementModel {
  id: number
  bomId: string
  bomTheme: string
  productNumber: string
  productName: string
  specification: string
  productId: string
  unit: string
  brand: string
  defaultBOM: string
  dailyOutput: string
  itemIds: string | null
  processFlowIds: string | null
}

interface QueryResponse {
  totaCount: number
  totaPage: number
  pageData: ManagementModel[]
  msg: string
  code: number
  data: unknown
}

const loading = ref(false)

const state = reactive({
  keyword: '',
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  items: [] as ManagementModel[]
})

const pageSizes = [5, 10, 20, 50]

// 注入MainLayout的方法
const addTab = inject('addTab') as ((key: string, label: string) => void) | undefined
const switchTab = inject('switchTab') as ((key: string) => void) | undefined

function handleAdd() {
  if (addTab && switchTab) {
    addTab('add-bom', '新增BOM')
    switchTab('add-bom')
  }
}

async function fetchData() {
  loading.value = true
  try {
    const response = await axios.post<QueryResponse>(
      'http://localhost:5233/api/Management/query',
      {
        pageIndex: state.pageIndex,
        pageSize: state.pageSize,
        keyword: state.keyword
      },
      {
        headers: { 'Content-Type': 'application/json' }
      }
    )

    const res = response.data
    if (res.code !== 200) {
      ElMessage.error(res.msg || '查询失败')
      return
    }
    state.items = res.pageData || []
    state.totalCount = res.totaCount || 0
  } catch (err: any) {
    console.error(err)
    ElMessage.error('请求失败，请检查后端接口')
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  state.pageIndex = 1
  fetchData()
}

function handleSizeChange(size: number) {
  state.pageSize = size
  state.pageIndex = 1
  fetchData()
}

function handleCurrentChange(page: number) {
  state.pageIndex = page
  fetchData()
}

function handleView(row: ManagementModel) {
  const tabKey = `bom-detail-${row.id}`
  try { sessionStorage.setItem(tabKey, JSON.stringify(row)) } catch {}
  if (addTab && switchTab) {
    addTab(tabKey, `BOM详情-${row.bomId}`)
    switchTab(tabKey)
  }
}

onMounted(fetchData)
</script>

<template>
  <div style="padding: 16px 20px;">
    <el-card shadow="never">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
        <div>
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <el-button>导入</el-button>
          <el-button>下载模板</el-button>
        </div>
        <div style="display: flex; gap: 8px; align-items: center;">
          <el-input
            v-model="state.keyword"
            placeholder="请输入关键字"
            clearable
            style="width: 260px;"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </div>
      </div>

      <el-table :data="state.items" v-loading="loading" border>
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="bomId" label="BOM编号" min-width="120" />
        <el-table-column prop="bomTheme" label="BOM主题" min-width="140" />
        <el-table-column prop="productNumber" label="成品编号" min-width="120" />
        <el-table-column prop="productName" label="成品名称" min-width="140" />
        <el-table-column prop="specification" label="规格型号" min-width="160" />
        <el-table-column prop="unit" label="单位" width="100" />
        <el-table-column prop="brand" label="品牌" width="120" />
        <el-table-column prop="defaultBOM" label="默认BOM" width="100" />
        <el-table-column prop="dailyOutput" label="日产量" width="100" />
        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="{ row }">
            <el-link type="primary">编辑</el-link>
            <el-divider direction="vertical" />
            <el-link type="danger">删除</el-link>
            <el-divider direction="vertical" />
            <el-link @click="handleView(row)">查看</el-link>
          </template>
        </el-table-column>
      </el-table>

      <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 12px;">
        <div>共 {{ state.totalCount }} 条数据</div>
        <el-pagination
          background
          layout="sizes, prev, pager, next, jumper"
          :total="state.totalCount"
          :current-page="state.pageIndex"
          :page-sizes="pageSizes"
          :page-size="state.pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
</style>

